package com.ljh.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author: Themberfue
 * @date: 2025/5/27 19:37
 * @description:
 */
@Slf4j
public class EventLoopClient4 {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();

        new Thread(() -> {
            Scanner sc = new Scanner(System.in);
            while (true) {
                String line = sc.nextLine();
                if (line.equals("q")) {
                    // ! 异步方法
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();

        // TODO way 1. 同步等待
//        syncProcess(channel);

        // TODO way 2. 异步处理
        asyncProcess(channel, group);

    }

    private static void asyncProcess(Channel channel, EventLoopGroup group) throws InterruptedException {
        ChannelFuture closeFuture = channel.closeFuture();
        // ! 调用 addListener(回调对象) 方法异步处理
        closeFuture.addListener(new ChannelFutureListener() {
            @Override // ? 等待 channel.close() 执行完后，执行该方法
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("channel 关闭后的善后处理");
                // ! channel 关闭后，由于 EventLoopGroup 里的线程并非守护线程，所以主线程结束后，整个 Java 进程不会退出
                // TODO 将 group 里的线程优雅地关闭
                group.shutdownGracefully();
            }
        });
    }

    private static void syncProcess(Channel channel) throws InterruptedException {
        ChannelFuture closeFuture = channel.closeFuture();
        log.debug("waiting close...");
        closeFuture.sync(); // ! 同步等待，等待 channel.close() 执行完后 main 继续往下执行
        log.debug("channel 关闭后的善后处理");
    }
}
